#include "stdafx.h"
#include "Events.h"
#include "utils.h"

/**
* Called before establishing an outgoing TCP connection,
* when NF_INDICATE_CONNECT_REQUESTS flag is specified in an appropriate rule.
* It is possible to change pConnInfo->filteringFlag and pConnInfo->remoteAddress
* in this handler. The changes will be applied to connection.
* @param id Unique connection identifier
* @param pConnInfo Connection parameters, see <tt>NF_TCP_CONN_INFO</tt>
**/
void ProxyEventHandler::tcpConnectRequest(ENDPOINT_ID id,
                                          PNF_TCP_CONN_INFO pConnInfo)
{
    if (!m_UserMgr)
        return;
    //test todo remove
    m_UserMgr->AddProxyUser(pConnInfo->processId, std::make_shared<AuthInfo>("104.167.65.37", 28553, "123", "123"));
    // end todo

    TAUTH auth = m_UserMgr->QueryProxyUser(pConnInfo->processId);

    if (auth)
    {
        unsigned char proxyAddress[NF_MAX_ADDRESS_LENGTH];
        int err,proxyAddressLen = NF_MAX_ADDRESS_LENGTH;
        err = WSAStringToAddress((LPSTR)mdk::format("%s:%d", auth->sIP.c_str(), auth->iPort).c_str(),
                           AF_INET, NULL, (LPSOCKADDR)proxyAddress, &proxyAddressLen);
        if (!err && m_TCPProxy)
        {
            m_TCPProxy->setProxy(id, TcpProxy::PROXY_SOCKS5, (LPSTR)proxyAddress,
                                 proxyAddressLen, auth->sName.c_str(), auth->sPassWord.c_str());
        }
    }
}

void ProxyEventHandler::senEventhandle(TcpProxy::TCPProxy* tcpHandle, UserMgr* umgrHandle)
{
    m_TCPProxy = tcpHandle;
    m_UserMgr = umgrHandle;
}